package com.javastar.common.interceptor;

import com.javastar.common.annotation.Login;
import com.javastar.common.bean.LoginUser;
import com.javastar.common.enums.TokenEnum;
import com.javastar.common.exception.ErrorCode;
import com.javastar.common.exception.NovelException;
import com.javastar.common.utils.JwtUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 权限(Token)验证
 *
 * @author Mark sunlightcs@gmail.com
 */
@Component
public class AuthorizationInterceptor extends HandlerInterceptorAdapter {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Login annotation;
        if (handler instanceof HandlerMethod) {
            annotation = ((HandlerMethod) handler).getMethodAnnotation(Login.class);
        } else {
            return true;
        }

        if (annotation == null) {
            return true;
        }

        // 从header中获取token
        String userToken = request.getHeader(TokenEnum.USER_TOKEN.getTokenKey());

        // 用户id
        LoginUser loginUser;

        // token为空
        if (StringUtils.isBlank(userToken)) {
            throw new NovelException(ErrorCode.TOKEN_EMPTY);
        }

        // token无效
        if (JwtUtil.validateToken(userToken, TokenEnum.USER_TOKEN) || (loginUser = JwtUtil.getBean(userToken, TokenEnum.USER_TOKEN, LoginUser.class)) == null) {
            throw new NovelException(ErrorCode.TOKEN_INVALID);
        }

        // 设置loginUser到request里，后续根据loginUser取出userId，获取用户信息
        request.setAttribute("loginUser", loginUser);

        return true;
    }
}
